<template>
  <view class="sort-popup" v-if="isShowSortPopup">
    <view style="background: #fff; border-radius: 0 0 20rpx 20rpx">
      <view
        :class="
          activeSortType === item.type ? 'active-sort-name' : 'sort-content'
        "
        v-for="(item, index) in sortList"
        :key="index"
      >
        <view class="sort-name" @click="handleClick(item)">
          {{ item.name }}
        </view>
      </view>
    </view>
    <view class="overlay" @click="close()"></view>
  </view>
</template>

<script setup>
import { ref, watch } from "vue";

const props = defineProps({
  isShowRate: {
    type: Boolean,
    default: false,
  },
});
const popup = ref();
const isShowSortPopup = ref(false);
const activeSortType = ref();
const baseSortList = ref([
  {
    name: "全部",
    type: 1,
  },
  {
    name: "价格最低",
    type: 2,
  },
  {
    name: "价格最高",
    type: 3,
  },
  {
    name: "保证金最低",
    type: 4,
  },
  {
    name: "订单时间最少",
    type: 5,
  },
]);
// 动态排序列表
const sortList = ref([...baseSortList.value]);

// 监听 isShowRate 变化，动态更新排序列表
watch(
  () => props.isShowRate,
  (newVal) => {
    if (newVal) {
      // 如果 isShowRate 为 true，添加"每星单价最高"选项
      const existingRateOption = sortList.value.find(
        (option) => option.type === 6
      );
      if (!existingRateOption) {
        sortList.value.push({
          name: "每星单价最高",
          type: 6,
        });
      }
    } else {
      // 如果 isShowRate 为 false，移除"每星单价最高"选项
      const rateOptionIndex = sortList.value.findIndex(
        (option) => option.type === 6
      );
      if (rateOptionIndex > -1) {
        sortList.value.splice(rateOptionIndex, 1);
      }
    }
  },
  { immediate: true }
); // immediate: true 确保初始化时也会执行
const emits = defineEmits(["updataSort"]);
const handleClick = (item) => {
  activeSortType.value = item.type;
  emits("updataSort", {
    type: item.type,
    name: item.name,
  });
};
const open = () => {
  isShowSortPopup.value = !isShowSortPopup.value;
  // popup.value.open()
};
const close = () => {
  isShowSortPopup.value = false;
  // popup.value.close()
};

defineExpose({
  open,
  close,
});
</script>

<style scoped lang="scss">
.sort-popup {
  position: absolute;
  left: 0;
  top: 28rpx;
  width: 100%;
  z-index: 999;
  background: rgba(0, 0, 0, 0.5);
  height: 100vh;
  margin-top: 30rpx;
  display: flex;
  flex-direction: column;

  .sort-content {
    display: flex;
    flex-direction: column;

    .sort-name {
      font-size: 28rpx;
      line-height: 60rpx;
      color: #000;
      text-align: center;
    }
  }

  .sort-content:last-child {
    padding-bottom: 20rpx;
  }

  .active-sort-name {
    font-size: 28rpx;
    line-height: 60rpx;
    color: #6f69e9;
    text-align: center;
  }

  .overlay {
    flex: 1;
    width: 100%;
  }
}
</style>
